package org.whuims.service.comment;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.whuims.entity.Comment;
import org.whuims.entity.Infor;
import org.whuims.repository.jpa.CommentDao;

import java.util.Map;

/**
 * Created by Roger on 2016/12/21.
 */
@Service
public class CommentService {

    @Autowired
    private CommentDao commentDao;

    public void save(Comment comment) {
        commentDao.save(comment);
    }

    public Page<Comment> pageByInfor(Infor infor, int pageNumber, int pageSize) {
        PageRequest pageRequest = new PageRequest(pageNumber - 1, pageSize, new Sort(Sort.Direction.DESC, "id"));
        return commentDao.findByInfor(infor, pageRequest);
    }

    public Page<Comment> getCommentListByInforId(Infor infor, Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType) {
        PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
        Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
        filters.put("infor", new SearchFilter("infor", SearchFilter.Operator.EQ, infor));
        Specification<Comment> spec = DynamicSpecifications.bySearchFilter(filters.values(), Comment.class);
        return commentDao.findAll(spec, pageRequest);
    }

    /**
     * 创建分页请求.
     */
    private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
        Sort sort = null;
        if (sortType == null) sortType = "auto";
        if ("auto".equals(sortType)) {
            sort = new Sort(Sort.Direction.DESC, "id");
        }
        return new PageRequest(pageNumber - 1, pagzSize, sort);
    }

    public void delete(Long id) {
        this.commentDao.delete(id);
    }
}
